package com.example.wwk.graduationpractice.SmackUtils;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.wwk.graduationpractice.Globalutils.FormatTools;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.stringencoder.Base64;
import org.jivesoftware.smackx.vcardtemp.packet.VCard;
import org.jivesoftware.smackx.vcardtemp.provider.VCardProvider;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by wwk on 2017/3/27.
 * 获取vcard 的头像信息
 */

public class GetVcardUtils {
    private static final int SET_IMAGE_SUCCESS = 1;

    //    获取用户VCard信息
//     @param connection
//     @param user
//    @return
//     @throws XMPPException
//
    public static VCard getUserVCard(AbstractXMPPConnection connection, String user)//bareJid
            throws XMPPException {
        VCard vcard = new VCard();
        // 加入这句代码，解决No VCard for
        ProviderManager.addIQProvider("vCard", "vcard-temp",new VCardProvider());
        try {
            vcard.load(connection, user + "@" + connection.getServiceName());
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        return vcard;
    }
//    通过Vcard来获取用户头像信息，可以把 InputStream 转换为自己想要的类型，InputStream 转Drawable
//     * 获取用户头像信息
//     *
//     * @param connection
//     * @param user
//     * @return

    public static Drawable getUserImage(AbstractXMPPConnection connection, String user) {

        ByteArrayInputStream bais = null;
        try {
            VCard vcard = getUserVCard(connection,user);
            if (vcard == null || vcard.getAvatar() == null)
                return null;            //当vCard的为null或者头像为null
            bais = new ByteArrayInputStream(vcard.getAvatar());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bais == null)
            return null;
        return FormatTools.getInstance().InputStream2Drawable(bais);
    }


    private static byte[] getFileBytes(File file) throws IOException {
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            int bytes = (int) file.length();
            byte[] buffer = new byte[bytes];
            int readBytes = bis.read(buffer);
            if (readBytes != buffer.length) {
                throw new IOException("Entire file not read");
            }
            return buffer;
        } finally {
            if (bis != null) {
                bis.close();
            }
        }
    }

//    * 上传头像
    private static void setUserImage(final AbstractXMPPConnection connection,
                                     final byte[] image, final Handler handler) throws XMPPException {
        final VCard card = new VCard();
        try {
            card.load(connection);
        } catch (SmackException.NoResponseException e) {
            e.printStackTrace();
        } catch (SmackException.NotConnectedException e) {
            e.printStackTrace();
        }
        new Thread() {
            @Override
            public void run() {
                try {
                    AndFilter filter = new AndFilter(new PacketIDFilter(
                            card.getPacketID()), new PacketTypeFilter(IQ.class));
//                    filter=new AndFilter();
                    PacketCollector collector = connection.createPacketCollector(filter);
                    String encodeImage = Base64.encodeToString(image);
                    card.setAvatar(image);
                    card.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
                            + encodeImage + "</BINVAL>", true);
                    Log.i("other", "上传头像的方法！");
                    card.save(connection);
                    IQ iq = (IQ) collector.nextResult(SmackConfiguration
                            .getDefaultPacketReplyTimeout());
                    if (iq != null && iq.getType() == IQ.Type.result) {//上传成功
                        Message msg = handler.obtainMessage();//省去了创建对象申请内存的开销
                        msg.what = SET_IMAGE_SUCCESS;
                        handler.sendMessage(msg);
                    }
                } catch (XMPPException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SmackException.NotConnectedException e) {
                    e.printStackTrace();
                } catch (SmackException.NoResponseException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

}
